i have a image and i draw that image on the canvas. now i want to change the source of the image and again draw the image in the canvas. i have tried the below code and here is the jsfiddler . canvas's drawing is not changing.... what to do?
HTML
<button onclick="change_2_new_image();">change_image()</button>
<img id="test" src="http://static.clickbd.com/global/classified/item_img/374646_0_original.jpg" alt="error" title="This is an image" />
<canvas id="myCanvas" width="320px" height="275px"><canvas>
JS
var img;
$(function () {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
img = document.getElementById("test");
img.ready = function () {
alert("asasas");
};
ctx.drawImage(img, 0, 0);
});
function change_2_new_image() {
$('#test').attr("src", "http://upload.wikimedia.org/wikipedia/en/9/9a/Grameenphone_Logo.png");
img = document.getElementById("test");
ctx.drawImage(img, 0, 0);
}
Your issue is with variable scope. You can't access ctx from the function.
function change_2_new_image() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$('#test').attr("src", "http://upload.wikimedia.org/wikipedia/en/9/9a/Grameenphone_Logo.png");
img = document.getElementById("test");
ctx.drawImage(img, 0, 0);
ctx.render()
}
The above should now work.
ctx is defined inside of your closure and not defined in change_2_new_image()
that's why the error message ReferenceError: ctx is not defined
is popping up in the console. After fixing that, you may also notice that the image at times, hasn't yet loaded. use jQuery's on('load', ... ) event. for more info, you can have a look at this thread: jQuery event for images loaded
Hope that helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.