简体   繁体   English

如何加载新图像并将其绘制到画布?

[英]how to load new image and draw it to the canvas?

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 . 我已经尝试了下面的代码,这里是jsfiddler canvas's drawing is not changing.... what to do? 画布的绘图没有改变......怎么办?

HTML 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 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. 您无法从该功能访问ctx。

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. ctx是在闭包内定义的,而不是在change_2_new_image()中定义的,这就是控制台中弹出错误消息ReferenceError: ctx is not defined的原因。 After fixing that, you may also notice that the image at times, hasn't yet loaded. 修复之后,您可能还会注意到图像有时尚未加载。 use jQuery's on('load', ... ) event. 使用jQuery('load',...)事件。 for more info, you can have a look at this thread: jQuery event for images loaded 有关更多信息,您可以查看此线程: 加载图像的jQuery事件

Hope that helps! 希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM