简体   繁体   English

为什么上一张图片在我的HTML5画布上绘制?

[英]Why does the previous image draw on my HTML5 canvas?

this code draws an image of the user's local computer on a canvas then slide it on some other canvases for slide puzzle game 此代码在画布上绘制用户本地计算机的图像,然后在其他一些画布上滑动以进行拼图游戏

function drawImage(event) {

        if (event.target.files.length <= 0) return;
        var files = event.target.files;
        var URL = window.URL || window.webkitURL;
        var img = $("#image")[0];

        img.src = URL.createObjectURL(files[0]);

        getCanvas("karajan").drawImage(img, 0, 0, img.width, img.height, 0, 0, 450, 450);

       ...........

    }

    function getCanvas(id) {
        var canvas = $("#" + id)[0];
        if (canvas.getContext) {
            return canvas.getContext("2d");
        }
        return undefined;
    }

and a tag that inputs image file from local computer 和一个从本地计算机输入图像文件的标签

<input type="file" accept="image/*" id="image_input" onchange="drawImage(event)"/>
<img id="image"/>

and when user want to change the image, the canvas will draw with previous image. 当用户要更改图像时,画布将使用先前的图像进行绘制。 I don't know why. 我不知道为什么 in the first lines of drawImage function image changes with newer image and draws on canvas 在drawImage函数的第一行中,图像会随着更新的图像而变化并在画布上绘制

The canvas does not clear itself, you have to tell it to clear. 画布不会自行清除,您必须告诉它清除。 You can either wipe the whole thing with, or a controlled area, using clearRect(x,y,w,h) . 您可以使用clearRect(x,y,w,h)擦除整个区域或在受控区域擦除整个区域。 After this, you can draw the new image. 之后,您可以绘制新图像。

I assume the image is not actually "loaded" until the current script terminates. 我认为在当前脚本终止之前,实际上不会“加载”映像。 That means you should listen to the load event of the image and only then draw it to the canvas. 这意味着您应该监听图像的加载事件,然后将其绘制到画布上。

I did some restructuring of your code as well. 我也对您的代码进行了一些重组。 If you already have jQuery available, use it: 如果您已经有了jQuery,请使用它:

$(function() {
    var URL = window.URL || window.webkitURL;
    var $image = $('#image').on('load', function() {
        // clear canvas here
        getCanvas("karajan")
            .drawImage(this, 0, 0, this.width, this.height, 0, 0, 450, 450);
        // ...
    });

    $('#image_input').on('change', function() {
        if (this.files.length === 0) return;

        $image.prop('src', URL.createObjectURL(this.files[0]));
    });
});

You should still clear the canvas though, as Kolink suggested. 但是,您仍然应该按照Kolink的建议清除画布。 Otherwise, if a new, smaller image is loaded, parts of the previous, larger image will still be visible. 否则,如果加载了新的较小图像,则先前较大图像的部分仍将可见。

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

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