简体   繁体   English

用Javascript在画布上显示图像?

[英]Display image in canvas with Javascript?

I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates? 我希望能够点击页面上的按钮并将图像加载到某些X,Y坐标的画布中?

The following code is what I have below. 以下代码是我在下面的代码。 I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page. 我希望图像位于image / photo.jpg或同一目录中,但最好是在主页的子目录中。

**Question: How to make a JPG show up in a canvas with the click of a button on the web page? **问题:如何通过单击网页上的按钮使JPG显示在画布中?

Code: 码:

<!DOCTYPE html>
<html>

<script>
    function draw(){  
        var ctx = document.getElementById("myCanvas").getContext("2d");  
        var img = new Image():  
      //  img.src = "2c.jpg";  
        img.src = "/images/2c.jpg";  

        ctx.drawImage(img,0,0);  
    }


</script>


<body background="Black">

<div align="center">
    <button type="button" onclick="draw()">Show Image on Canvas</button> 

    <canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.
    </canvas>
</div>

<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.font="20px Arial";

    ctx.fillText("Royal Flush     $",500,50);
    ctx.fillText("Striaght Flush  $",500,80);
    ctx.fillText("Flush           $",500,110);
    ctx.fillText("Four of a Kind  $",500,140);
    ctx.fillText("Full House      $",500,170);
    ctx.fillText("Three of a Kind $",500,200);
    ctx.fillText("Two Pair        $",500,230);
    ctx.fillText("Pair of ACES    $",500,260);


    ctx.rect(495,10,270,350);
    ctx.stroke();
</script>

</body>
</html>

March 6th, 2014 Code: 2014年3月6日代码:

How is the following code not working. 以下代码如何不起作用。 Do you have to have an ID tag on Canvas. 你必须在Canvas上有一个ID标签。 The page will display but for some reason the image will not when the button is clicked. 页面将显示但由于某种原因,单击按钮时图像不会显示。 The image is in the same directory that my index.html file is in. 该图像与index.html文件所在的目录位于同一目录中。

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>

<style type="text/css">
    canvas{
       border: 5px solid black;
    }
</style>

</html>
    <button id="galaxy">Add image #1</button>
    <button id="circles">Add image #2</button><span></span>
    <canvas width="500" height="500"></canvas>

<script>
  var Images = {};

function loadImages(list){
    var total = 0;
    document.querySelector("span").innerText = "...Loading...";
    for(var i = 0; i < list.length; i++){
        var img = new Image();
        Images[list[i].name] = img;
        img.onload = function(){
            total++;
            if(total == list.length){
                document.querySelector("span").innerText = "...Loaded.";
            }
        };
        img.src = list[i].url;
    }
}

function drawImage(img){
    var ctx = document.querySelector("canvas").getContext("2d");
    ctx.drawImage(Images[img], 0, 0, 50, 50);
}

loadImages([{
    name: "2c.jpg",
    url: "mp.jpg"
},{
    name: "mp.jpg",
    url: "mp.jpg"
}]);

document.querySelector("#galaxy").addEventListener("click", function(){
    drawImage("galaxy");
});

document.querySelector("#circles").addEventListener("click", function(){
    drawImage("weirdCircles");
});

</script>   

</html>

Wait till the image is loaded before drawing: 等到图像加载后再绘制:

var img = new Image();
img.onload = function(){        /*or*/  img.addEventListener("load", function(){
    ctx.drawImage(img,0,0);                 ctx.drawImage(img,0,0);
};                                      };
img.src = "/images/2c.jpg";  

Demo: http://jsfiddle.net/DerekL/YcLgw/ 演示: http//jsfiddle.net/DerekL/YcLgw/


If you have more than one image in your game, 如果您的游戏中有多个图像,

It is better to preload all images before it starts. 最好在开始之前预加载所有图像。

Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/ ) 预加载图片: http//jsfiddle.net/DerekL/uCQAH/ (没有jQuery: http//jsfiddle.net/DerekL/Lr9Gb/


If you are more familiar with OOP : http://jsfiddle.net/DerekL/2F2gu/ 如果您对OOP更熟悉: http//jsfiddle.net/DerekL/2F2gu/

function ImageCollection(list, callback){
    var total = 0, images = {};   //private :)
    for(var i = 0; i < list.length; i++){
        var img = new Image();
        images[list[i].name] = img;
        img.onload = function(){
            total++;
            if(total == list.length){
                callback && callback();
            }
        };
        img.src = list[i].url;
    }
    this.get = function(name){
        return images[name] || (function(){throw "Not exist"})();
    };
}

//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
    name: "MyImage", url: "//example.com/example.jpg"
}]);

//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);

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

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