你可以在javascript文件中加载一个img标签的src,然后将它绘制到画布上吗?

时间:2013-03-20 16:43:14

标签: javascript html canvas

的index.html

<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=8" />
    <title>DCView</title>

    <script type="text/javascript" src="dcview.js"></script>
</head>
<body>
    <div style="float:center; text-align:center;">
        <canvas id="dcviewCanvas" width="1024" height="1024"/>
        <img id="bgImage" src="" hidden="true"/>
    </div>
</body>
</html>

dcview.js

var backgroundImage,
    backgroundImageSrc,
    canvas,
    context;

window.onload = function()
{
    //Initially set the background image source to DCView.png
    backgroundImageSrc = "Foundation\\WebService\\Downloads\\DCView.png";

    //Load the background image with the given source
    loadBackgroundImage(backgroundImageSrc);
}

function loadBackgroundImage(imageSrc)
{
    canvas = document.getElementById("dcviewCanvas");
    context = canvas.getContext("2d");

    backgroundImage = document.getElementById("bgImage");
    backgroundImage.src = imageSrc;

    context.drawImage(backgroundImage, 0, 0);
}

当我尝试在chrome中加载index.html时,它不会加载背景图像。但是当我将img标记的src硬编码到该路径时,它会继续加载它。

chrome给我的唯一错误是:

  

Uncaught SyntaxError:意外的令牌。

它将此错误指向dcview.js中的第47行。

我这样做的方式完全错了吗?我是HTML和Javascript的初学者。

谢谢,

Virat

已更新

dcview.js

window.onload = function()
{
    //Initially set the background image source to DCView.png
    backgroundImageSrc = 'Foundation/WebService/Downloads/Layout_Basement.png';

    //Load the background image which is initially set to DCView.png
    loadBackgroundImage(backgroundImageSrc);

    //Load the other various pin images;
    loadPinImages();
}

function loadBackgroundImage(imageSrc)
{
    context = document.getElementById('dcviewCanvas').getContext('2d');

    backgroundImage = new Image();
    backgroundImage.src = imageSrc;

    backgroundImage.onload = function(){
        context.drawImage(backgroundImage, 0, 0);
    };
}

已更新

一旦我加载了背景图像,我在顶部绘制的其他图像将被绘制在背景图像下方。想法?

window.onload = function()
{
    //Initially set the background image source to DCView.png
    backgroundImageSrc = 'Foundation/WebService/Downloads/Layout_Basement.png';

    //Load the background image which is initially set to DCView.png
    loadBackgroundImage(backgroundImageSrc);

    canvas = document.getElementById('dcviewCanvas');
    context = canvas.getContext('2d');
    context.drawImage(sortationLanePinBlue, 0, 0);
}

1 个答案:

答案 0 :(得分:1)

您可以使用Javascript Image类绘制到画布。 See this article on MDN