简体   繁体   中英

Moving imported image in canvas

I have a problem with moving image when importing it into a canvas. I tried this code but it doesn't work. The code simply drag an image into the canvas and it worked but when I tried to move it it doesn't move. Can anyone tell me where is the error. Here is the code:

<body>
<section>

<div>
<canvas id="canvas" width="300" height="200" style="border:1px solid" >
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<input  type="button" name="save" value="Drag Image" onClick="drag()"/>

</div>

<script type="text/javascript">

function drag(){
context.fillText("Drop an image onto the canvas", 50, 30);

var dx = 5;
var dy = 5;
var x = 170
var y = 100;
var img = new Image();
        hasText = true,
    clearCanvas = function () {
    if (hasText) {context.clearRect(0, 0, canvas.width, canvas.height);
    hasText = false;
                                }
                            };
        img.addEventListener("load", function() {
        clearCanvas();
    context.drawImage(img, x, y);
    }, false);


        // To enable drag and drop
    canvas.addEventListener("dragover", function (evt) {
       evt.preventDefault();}, false);

      // Handle dropped image file - only Firefox and Google Chrome
      canvas.addEventListener("drop", function (evt) {
     var files = evt.dataTransfer.files;
     if (files.length > 0) {
     var file = files[0];
     if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) {
    var reader = new FileReader();

    reader.onload = function (evt) {
    img.src = evt.target.result;
   };
   reader.readAsDataURL(file);}
    }
   evt.preventDefault();}, false);



function doKeyDown(evt){
  switch (evt.keyCode) {
    case 38:  /* Up arrow was pressed */
        if (y - dy > 0){ 
        y -= dy;
      }
      break;
    case 40:  /* Down arrow was pressed */
        if (y + dy < c){ 
        y += dy;
      }
      break;
    case 37:  /* Left arrow was pressed */
        if (x - dx > 0){ 
        x -= dx;
      }
      break;
    case 39:  /* Right arrow was pressed */
        if (x + dx < canvas.width){ 
        x += dx;
      }
      break;
  }
}
function draw(){
clearCanvas();
context.drawImage(img, x, y);}

img.addEventListener('keydown',doKeyDown,true);
}
</script>
<script type="text/javascript">

canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
setInterval(draw,5);

</script>

</section>
</body>
</html>

There are some small syntax errors that caused some errors, if you are using firefox you should try taking a look into using either the built in javascript error console for firefox ( Tools -> Error Console ) or firebug or if you use chrome the built in console ( Tools -> Javascript console ) and that should help you debug you're script. It seems that keydown events attached to the canvas or canvas elements don't trigger, settings the keydown event listener to attach to the window instead seems to make it function properly. Also the loading code doesn't seem to work in chrome, but it would be something to look into as a separate issue.

<html>
<head>
<title>Test Page</title>
</head>
<body>

<canvas id="canvas" width="300" height="200" style="border:1px solid" >
    This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<input  type="button" name="save" value="Drag Image" onClick="drag()"/>

<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

function drag(){
    context.fillText("Drop an image onto the canvas", 50, 30);
}

var dx = 5;
var dy = 5;
var x = 170
var y = 100;
var img = new Image();
hasText = true;

clearCanvas = function () {
    if (hasText) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        hasText = false;
    } else {
        context.clearRect(0, 0, canvas.width, canvas.height);
    }
};

img.addEventListener("load", function() {
    clearCanvas();
    context.drawImage(img, x, y);
}, false);

// To enable drag and drop
canvas.addEventListener("dragover", function (evt) {
    evt.preventDefault();
}, false);

// Handle dropped image file - only Firefox and Google Chrome
canvas.addEventListener("drop", function (evt) {
var files = evt.dataTransfer.files;
if (files.length > 0) {
    var file = files[0];
    if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) {
        var reader = new FileReader();
        reader.onload = function (evt) {
            img.src = evt.target.result;
        };
        reader.readAsDataURL(file);
    }
}
evt.preventDefault();
}, false);

function doKeyDown(evt){
    console.log(evt.keyCode);
    switch (evt.keyCode) {
    case 38:  /* Up arrow was pressed */
        if (y - dy > 0){ 
            y -= dy;
        }
        break;
    case 40:  /* Down arrow was pressed */
        if (y + dy < canvas.height){ 
            y += dy;
        }
        break;
    case 37:  /* Left arrow was pressed */
        if (x - dx > 0){ 
            x -= dx;
        }
        break;
    case 39:  /* Right arrow was pressed */
        if (x + dx < canvas.width){ 
            x += dx;
        }
        break;
    }
    draw();
}

function draw(){
    clearCanvas();
    context.drawImage(img, x, y);
}

window.addEventListener('keydown', doKeyDown, false);

//setInterval(draw,5);
</script>
</body>
</html>

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.

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