In the code below there are two canvases clicking on which will open the file browser to open an image. I want to display the opened image in that canvas which was clicked. but
1) the problem is once the control is inside the handleFile I don't know which one of the canvases was originally clicked! how can I do that or how can I pass the canvas as parameter to the function handleFile ?
2)what if I wanted to write something onto textarea1 when clicked on canvas1, write to textarea2 when clicked on canvas2?
<html>
<head>
</head>
<body>
<input type="file" id="fileLoader" name="fileLoader" style="display: none" />
<canvas id="bufferCanvas"></canvas>
<canvas id="canvas1" width="200" height="200" style="cursor:pointer; border:2px solid #000000"></canvas>
<canvas id="canvas2" width="200" height="200" style="cursor:pointer; border:2px solid #ff6a00"></canvas>
<textarea id="textarea1" rows="4" cols="50"></textarea>
<textarea id="textarea2" rows="4" cols="50"></textarea>
<script src="upload.js"></script>
</body>
</html>
and here is upload.js
var fileLoader = document.getElementById('fileLoader');
var bufferCanvas = document.getElementById('bufferCanvas');
var allCanvases = document.getElementsByTagName("Canvas");
for (var i = 1; i < allCanvases.length; ++i) {
allCanvases[i].getContext("2d").fillStyle = "blue";
allCanvases[i].getContext("2d").font = "bold 20px Arial";
allCanvases[i].getContext("2d").fillText("image " + i + " of 1", 22, 20);
allCanvases[i].onclick = function (e) {
fileLoader.click(e);
}
}
fileLoader.addEventListener('change', handleFile, false);
var textarea1 = document.getElementById('textarea1');
var ctx = bufferCanvas.getContext('2d');
function handleFile(e) {
// I wanna know what canvas was clicked
//So I can display the image on the canvas which was clicked
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
bufferCanvas.width = img.width;
bufferCanvas.height = img.height;
ctx.drawImage(img, 0, 0);
dataURL = bufferCanvas.toDataURL('image/png'); // here is the most important part because if you dont replace you will get a DOM 18 exception;
// window.location.href = dataURL;// opens it in current windows for testing
textarea1.innerHTML = dataURL;
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
The problem is the onclick for the canvas is firing a click for the fileloader which has it's own event. To do what you want you can create global var to hold the <canvas> that was clicked.
var fileLoader = document.getElementById('fileLoader');
var bufferCanvas = document.getElementById('bufferCanvas');
var allCanvases = document.getElementsByTagName("Canvas");
var clickedCanvas = ''; //<---- will hold the triggering canvas
Then in your onclick function you can set html element to clickedCanvas
for (var i = 1; i < allCanvases.length; ++i) {
...
...
...
allCanvases[i].onclick = function (e) {
clickedCanvas = e.srcElement; // <--- set the clicked on canvas
fileLoader.click(e);
}
}
Now in function handleFile(e) you should be able to get the canvas from clickedCanvas
Also I would clear out clickedCanvas after you are done so you aren't retaining the last event.
Fiddle
Related
PS: Is it not a research kind of question! I have been trying to do this from very long time.
I am trying to make web based an image editor where user can select multiple cropping area and after selection save/download all the image area. like below.
As of now I discovered two libraries
1.Cropper.JS where is only single selection feature is available.
2.Jcrop where only single selection area restrictions.
I am currently using cropper.Js but it seems impossible for me to make multiple selection cropping.
Any help is much appreciated.if any other method/library available in JavaScript, Angular or PHP or reactJS for multiple image area selection and crop and download in one go as in the image below.
As per #Keyhan Answer I am Updating my Jcrop library Code
<div style="padding:0 5%;">
<img id="target" src="https://d3o1694hluedf9.cloudfront.net/market-750.jpg">
</div>
<button id="save">Crop it!</button>
<link rel="stylesheet" href="https://unpkg.com/jcrop/dist/jcrop.css">
<script src="https://unpkg.com/jcrop"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
JavaScript
<script>
setImage();
var jcp;
var jcp;
Jcrop.load('target').then(img => {
//You can enable multiple cropping with this line:
jcp = Jcrop.attach(img, { multi: true });
});
// to fix security issue when trying to convert to Data URI
function setImage() {
document.getElementById('target').setAttribute('crossOrigin', 'anonymous');
document.getElementById('target').src = 'https://d3o1694hluedf9.cloudfront.net/market-750.jpg';
}
var link = document.getElementById('save');
link.onclick = function () {
//we check if at least one crop is available
if (jcp.active) {
var i = 0;
var fullImg = document.getElementById("target");
//we are looping cropped areas
for (area of jcp.crops) {
i++;
//creating temp canvas and drawing cropped area on it
canvas = document.createElement("canvas");
canvas.setAttribute('width', area.pos.w);
canvas.setAttribute('height', area.pos.h);
ctx = canvas.getContext("2d");
ctx.drawImage(fullImg, area.pos.x, area.pos.y, area.pos.w, area.pos.h, 0, 0, area.pos.w, area.pos.h);
//creating temp link for saving/serving new image
temp = document.createElement('a');
temp.setAttribute('download', 'area' + i + '.jpg');
temp.setAttribute('href', canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream"));
temp.click();
}
}
};
</script>
I tried to explain the code with comments:
var jcp;
Jcrop.load('target').then(img => {
//You can enable multiple cropping with this line:
jcp = Jcrop.attach(img,{multi:true});
});
//assuming you have a button with id="save" for exporting cropped areas
var link=document.getElementById('save');
link.onclick = function(){
//we check if at least one crop is available
if(jcp.active){
var i=0;
var fullImg = document.getElementById("target");
//we are looping cropped areas
for(area of jcp.crops){
i++;
//creating temp canvas and drawing cropped area on it
canvas = document.createElement("canvas");
canvas.setAttribute('width',area.pos.w);
canvas.setAttribute('height',area.pos.h);
ctx = canvas.getContext("2d");
ctx.drawImage(fullImg, area.pos.x, area.pos.y, area.pos.w, area.pos.h, 0, 0, area.pos.w, area.pos.h);
//creating temp link for saving/serving new image
temp = document.createElement('a');
temp.setAttribute('download', 'area'+i+'.jpg');
temp.setAttribute('href', canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream"));
temp.click();
}
}
};
EDIT: As you commented it would be nicer if we have local image loader, we can add a file input to our html
<img id="target" />
<br/>
<input type="file" id="imageLoader" name="imageLoader"/><!-- add this for file picker -->
<button id="save">save</button>
and a function to our js to handle it
var jcp;
var save=document.getElementById('save');
var imageLoader = document.getElementById('imageLoader');
var img = document.getElementById("target");
imageLoader.onchange=function handleImage(e){//handling our image picker <input>:
var reader = new FileReader();
reader.onload = function(event){
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
save.onclick = function(){
if(jcp&&jcp.active){
var i=0;
for(area of jcp.crops){
i++;
canvas = document.createElement("canvas");
canvas.setAttribute('width',area.pos.w);
canvas.setAttribute('height',area.pos.h);
ctx = canvas.getContext("2d");
ctx.drawImage(img, area.pos.x, area.pos.y, area.pos.w, area.pos.h, 0, 0, area.pos.w, area.pos.h);
temp = document.createElement('a');
temp.setAttribute('download', 'area'+i+'.jpg');
temp.setAttribute('href', canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream"));
temp.click();
}
}
};
Jcrop.load('target').then(img => {
jcp = Jcrop.attach(img,{multi:true});
});
Yes, #keyhan was right <input type="file"> is another question, but still, I am giving you an idea of how to implement Kayhan's code above.
<div>
<input type="file" id="image-input" accept="image/*">
<!-- img id name should be "target" as it is also using by Jcrop -->
<img id="target"></img>
</div>
and Now you can put below JavaScript Code just above setImage()
<script>
let imgInput = document.getElementById('image-input');
imgInput.addEventListener('change', function (e) {
if (e.target.files) {
let imageFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("img");
img.onload = function (event) {
var MAX_WIDTH = 1600;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
// Change the resizing logic
if (width > height) {
if (width > MAX_WIDTH) {
height = height * (MAX_WIDTH / width);
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width = width * (MAX_HEIGHT / height);
height = MAX_HEIGHT;
}
}
// Dynamically create a canvas element
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
// var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Actual resizing
ctx.drawImage(img, 0, 0, width, height);
// Show resized image in preview element
var dataurl = canvas.toDataURL(imageFile.type);
document.getElementById("target").src = dataurl;
}
img.src = e.target.result;
}
reader.readAsDataURL(imageFile);
}
});
</script>
I'm Currently Trying to apply a filter or filters to a Canvas Image after its been uploaded to the page and but if they want to change filters to more blurry or to another filter it removes the image and you will have to re-upload the image. I plan on making it where there is a button to several different filters and then they click on the filter they want to apply to the image. Any Ideas on How to fix it?
Right now when you go to upload the image, it will blur it to 5px but if you want it less or more blurry for example it will remove the image.
Thank You! In advance! Heres a Live Link of my code:
https://jsfiddle.net/mbyvvszy/
html:
<canvas id="canvas" width="1000" height="500" class="playable-canvas"></canvas>
<div id="image_div">
<h1> Choose an Image to Upload </h1>
<input type='file' name='img' id='uploadimage' />
</div>
<div class="playable-buttons">
<input id="edit" type="button" value="Edit" />
<input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.filter = 'blur(5px)';
</textarea>
Javascript :
var drawnImage;
function drawImage(ev) {
console.log(ev);
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.URL || window.webkitURL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
drawnImage = img;
ctx.drawImage(img, 0, 0);
url.revokeObjectURL(src);
}
}
document.getElementById("uploadimage").addEventListener("change", drawImage, false);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var edit = document.getElementById('edit');
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
}
reset.addEventListener('click', function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener('click', function() {
textarea.focus();
})
textarea.addEventListener('input', drawCanvas);
window.addEventListener('load', drawCanvas);
In drawCanvas, you clear the canvas but never re-draw the image. Just add a call to drawImage.
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
drawImage();
}
I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?
The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.
**Question: How to make a JPG show up in a canvas with the click of a button on the web page?
Code:
<!DOCTYPE html>
<html>
<script>
function draw(){
var ctx = document.getElementById("myCanvas").getContext("2d");
var img = new Image():
// img.src = "2c.jpg";
img.src = "/images/2c.jpg";
ctx.drawImage(img,0,0);
}
</script>
<body background="Black">
<div align="center">
<button type="button" onclick="draw()">Show Image on Canvas</button>
<canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Arial";
ctx.fillText("Royal Flush $",500,50);
ctx.fillText("Striaght Flush $",500,80);
ctx.fillText("Flush $",500,110);
ctx.fillText("Four of a Kind $",500,140);
ctx.fillText("Full House $",500,170);
ctx.fillText("Three of a Kind $",500,200);
ctx.fillText("Two Pair $",500,230);
ctx.fillText("Pair of ACES $",500,260);
ctx.rect(495,10,270,350);
ctx.stroke();
</script>
</body>
</html>
March 6th, 2014 Code:
How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
canvas{
border: 5px solid black;
}
</style>
</html>
<button id="galaxy">Add image #1</button>
<button id="circles">Add image #2</button><span></span>
<canvas width="500" height="500"></canvas>
<script>
var Images = {};
function loadImages(list){
var total = 0;
document.querySelector("span").innerText = "...Loading...";
for(var i = 0; i < list.length; i++){
var img = new Image();
Images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
document.querySelector("span").innerText = "...Loaded.";
}
};
img.src = list[i].url;
}
}
function drawImage(img){
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(Images[img], 0, 0, 50, 50);
}
loadImages([{
name: "2c.jpg",
url: "mp.jpg"
},{
name: "mp.jpg",
url: "mp.jpg"
}]);
document.querySelector("#galaxy").addEventListener("click", function(){
drawImage("galaxy");
});
document.querySelector("#circles").addEventListener("click", function(){
drawImage("weirdCircles");
});
</script>
</html>
Wait till the image is loaded before drawing:
var img = new Image();
img.onload = function(){ /*or*/ img.addEventListener("load", function(){
ctx.drawImage(img,0,0); ctx.drawImage(img,0,0);
}; };
img.src = "/images/2c.jpg";
Demo: http://jsfiddle.net/DerekL/YcLgw/
If you have more than one image in your game,
It is better to preload all images before it starts.
Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)
If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/
function ImageCollection(list, callback){
var total = 0, images = {}; //private :)
for(var i = 0; i < list.length; i++){
var img = new Image();
images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
callback && callback();
}
};
img.src = list[i].url;
}
this.get = function(name){
return images[name] || (function(){throw "Not exist"})();
};
}
//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
name: "MyImage", url: "//example.com/example.jpg"
}]);
//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);
Hi there I have been trying to save my canvas as a png and generate it to the web page as soon as it is complied. The problem i am having is that when the image is saved and outputted it only shows the text that i load in from a text box. I also load in a background image which shows in the canvas but not in the outputted image.
<form>
<input name="name" id="name" type="text"/>
</form>
<canvas id="myCanvas" width="640" height="480"></canvas>
<input name="" type="button" onclick="save()" /> Generate
<div id="sample">
</div>
<script type="text/javascript" src="canvas.js"></script>
java script
var myCanvasElement=document.getElementById("myCanvas");
var drawingContext=myCanvasElement.getContext("2d");
// clear canvas and div
drawingContext.clearRect ( 0 , 0 , 640 , 480 );
document.getElementById("sample").innerHTML = "";
// add text box text to canvas
var amount1 = document.getElementById("name").value;
drawingContext.font = "bold 12px sans-serif";
drawingContext.fillText(amount1, 30, 43);
drawingContext.fillText(amount1, 30, 43);
//loads in image to canvas
var imageObj = new Image();
imageObj.onload = function() {
drawingContext.drawImage(imageObj, 100, 150);
};
imageObj.src ='132.png';
//converts canvas to image
var canvas = document.getElementById('myCanvas'),
dataUrl = canvas.toDataURL(),
imageFoo = document.createElement('img');
imageFoo.src = dataUrl;
//Style your image here
imageFoo.style.width = '640px';
imageFoo.style.height = '480px';
//After you are done styling it, append it to the BODY element
var theDiv = document.getElementById("sample");
theDiv.appendChild(imageFoo);
}
I was wondering if anyone had any suggestions as to why it might be doing this
Thank you in advance
Give time to load the image . when its is loaded then convert it to DataUrl.
Try this :
// your code
var imageObj = new Image();
imageObj.onload = function() {
drawingContext.drawImage(imageObj, 100, 150);
setTimeout(loadImage,200) ;
};
imageObj.src ='132.png';
After image is loaded call this :
function loadImage()
{
//converts canvas to image
var canvas = document.getElementById('myCanvas'),
dataUrl = canvas.toDataURL(),
imageFoo = document.createElement('img');
imageFoo.src = dataUrl;
//Style your image here
imageFoo.style.width = '640px';
imageFoo.style.height = '480px';
//After you are done styling it, append it to the BODY element
var theDiv = document.getElementById("sample");
theDiv.appendChild(imageFoo);
}
I am uploading an image from PC. Then I read the file with file reader and display image by creating an img tag. Then I drag the image from the img tag into the canvas and draw it onto canvas. I'm using dragstart and onDrop events. I use datatransfer.setdata() and datatransfer.getdata() for the functionality. But on drop, the image drawn on canvas is not as original. It is a zoomed version. I don't know why is this happening!
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag Demo</title>
<link href="copy.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div style = "border:2px solid black;">
<canvas id = "canvas" style = "position:relative;width:1000px;height:1000px;top:0px;left:200px; border:2px solid black;" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </canvas>
</div>
<div>
<input type="file" id="fileElem" accept="image/*" style="display:none" >
<div id="fileSelect" class="drop-area">Select some files</div>
</div>
<div id="thumbnail"></div>
</div>
<script type="text/javascript">
function dragIt(event) {
event.dataTransfer.setData("URL", event.target.id)
};
function dropIt(event) {
var theData = event.dataTransfer.getData("URL");
dt = document.getElementById(theData);
alert(dt.width);
alert(dt.height);
event.preventDefault();
var c = document.getElementById("canvas");
var ctx = c.getContext('2d');
ctx.drawImage(dt, 0, 0);
};
var count = 0;
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem");
fileElem.addEventListener("change",function(e){
var files = this.files
handleFiles(files)
},false)
fileSelect.addEventListener("click", function (e) {
fileElem.click();
e.preventDefault();
}, false);
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
var thumbnail = document.getElementById("thumbnail");
image.file = file;
function handlefilereader(evt){
var target = evt.target || evt.srcElement;
image.src = evt.target.result;
}
if(document.all) {
image.src = document.getElementById('fileElem').value;
}
else {
var reader = new FileReader()
reader.onload = handlefilereader;
reader.readAsDataURL(file);
}
image.id = count;
count++;
thumbnail.appendChild(image);
alert(image.width);
image.draggable = true;
image.ondragstart = dragIt;
}
}
</script>
</body>
</html>
With canvas there are 2 'size' settings:
Through CSS you'll set the DISPLAY size, so to set the PHYSICAL size of the canvas, you MUST use its attributes. So NO CSS/Style.
Think about it this way: you create a IMAGE with physical size: (let's say) 400px*400px.
Then just as a normal image (jpg,png,gif) that has a physical size, you can still choose to change the DISPLAYED size and thus aspect-ratio: like 800px*600px. Even % is normally supported.
Hope this explains clearly WHY this happened and why your solution in your comment is also the correct solution!!