【问题标题】:Draw images on HTML5 canvas在 HTML5 画布上绘制图像
【发布时间】:2014-07-10 12:18:21
【问题描述】:

我想在画布上绘制图像,但图像只会出现在我点击画布的位置。我还了解到element.getBoundingClientRect 方法可以让我获得画布的偏移量。我想将它们组合起来,所以当点击画布的任何部分时,图像会出现在同一位置,并且 X 和 Y 偏移也会显示出来。

目前我的图像将在加载时显示,当我在画布上单击时如何更改它,图像将出现在同一位置。第二件事是图像的X和Y偏移位置也会同时显示出来。

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    像这样修改你的 JS 代码:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    $results=$("#results");
    $dotposition=$("#dotposition");
    var position = {x: 0, y: 0};
    
    function handleMouseMove(e) {
        e.preventDefault();
        e.stopPropagation();
    
        // You could calc the offsets once if you know
        // the user will not scroll the canvas
        var BB=canvas.getBoundingClientRect();
        var offsetX=BB.left;
        var offsetY=BB.top;
    
        mouseX=parseInt(e.clientX-offsetX);
        mouseY=parseInt(e.clientY-offsetY);
        $results.text("Mouse position: "+mouseX+" / "+mouseY);
        position.x = mouseX;
        position.y = mouseY;
    }
    
    function handleMouseClick(e) {
        //Clearing the canvas before redraw, remove this line if you want to keep prev images
        ctx.clearRect ( 0 , 0 , canvas.width , canvas.height );
    
        ctx.drawImage(img,position.x - img.width / 2,position.y - img.height / 2);
        $dotposition.text("Dot position: "+position.x+" / "+position.y);
    }
    
    var img = new Image();
    img.onload = function(){
        canvas.onmousemove = handleMouseMove;
        canvas.onclick = handleMouseClick;
    };
    img.src="https://dl.dropboxusercontent.com/s/7vlxwy1156wnhcw/redFood.png";
    

    http://jsfiddle.net/ZH4KW/1/

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多