首页 > 解决方案 > 如何使用画布 getImageData() 和 putImageData() 复制画布的一部分并将其粘贴到另一个位置?

问题描述

它看起来很简单,但它让我很头疼。

我想要完成的是:

我当前的代码如下所示:

<script type="text/javascript">
    var obj=document.getElementById("test"), img=document.getElementById("testimg");
    //obj is the canvas object and img is an image object

    var cvs=obj.getContext("2d"), imgdata;
    //getting ready to draw

    cvs.fillStyle="#006060";

    sym(lambda,50,50,cvs);
    //this is an external function, which draws a small image on the canvas by putting its pixels, one by one, on the canvas

    img.onload=function(){
        cvs.drawImage(img,150,150);
        }
    //drawing the image loaded from file with <img /> on to the canvas

    imgdata=cvs.getImageData(150,150,18,18);
    //copying the part of image we need (this is the image we put on canvas from the file). its dimensions are 18 x 18

    cvs.putImageData(imgdata,100,100);
    //trying to put the image on location (100,100) on the canvas. this is where it is failing me
</script>

我在这里做错了什么?应该怎么做?

w3schools 网站上有一个非常简洁的 getImageData() 和 putImageData() 示例,在他们的尝试自己的页面上。当我尝试复制此过程以供自己使用时,一切都崩溃了。

我哪里错了?

标签: html5-canvasgetimagedataputimagedata

解决方案


推荐阅读