HTML使用canvas載入圖片

乞力馬紮羅的雪CYF發表於2015-09-27

(1)JS實現程式碼如下:

/**
 * Created by chenyufeng on 15/9/27.
 */
var CANVAS_WIDTH = 500, CANVAS_HEIGHT = 500;
var mycanvas,context;

window.onload = function(){

    createCanvas();
    drawImage();

};

function createCanvas(){

    document.body.innerHTML = "<canvas id=\"mycanvas\" width=\""+CANVAS_WIDTH+"\" height=\""+CANVAS_HEIGHT+"\"></canvas>";

    mycanvas = document.getElementById("mycanvas");
    context = mycanvas.getContext("2d");

}

function drawImage(){

    var img = new Image();
    img.onload = function(){

        context.drawImage(img,0,0);
    };
    img.src = "1.png";

}






(2)HTML程式碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <script src="app.js"></script>

</body>
</html>

實現要拖入一張圖片。



github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!

相關文章