0

我在我的网站上使用了这段代码,但是当页面打开时图像没有加载,我希望图像从启动开始加载,然后一个简单的鼠标悬停在单击时更改图像和链接。我不擅长编码,所以任何帮助都会很好。

这是我使用的代码。

<!doctype html>
<html>
 <body>
 <head>
  <script>
    function init() {
        setImageOne();
    }

    function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }

    function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }

    function setImage(src) {
        var canvas = document.getElementById("e");
        var context = canvas.getContext("2d");
        if (context == null) return;
        var img = new Image();
        img.src = src;
        context.drawImage(img, 0, 0, 322, 200);
    }
  </script>
</head>

浏览器不支持画布

4

3 回答 3

1

在绘制之前,您需要等待图像加载。此外,如果您的浏览器不支持画布,那么这种方法对您没有任何帮助。

function setImage(src) {
    var canvas = document.getElementById("e");
    var context = canvas.getContext("2d");
    if (context == null) return;
    var img = new Image();
    img.onload = function () {
        context.drawImage(img, 0, 0, 322, 200);
    };
    img.src = src;

}
于 2013-06-07T23:48:12.210 回答
0

您应该等待图像加载。因此,您的代码应该是(有关 html 标记的更正):

<!DOCTYPE html>
<html lang="en-us">
    <head>
        <meta charset="utf-8">
  </head>
  <body>
    <canvas id="e" style="width: 100%; height: 100%;"></canvas>
  <script>
    function init() {
        setImageOne();
    }

    function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }

    function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }

    function setImage(src) {
        var canvas = document.getElementById("e");
        var context = canvas.getContext("2d");
        if (context == null) return;
        var img = new Image;
        img.onload = function (){
            context.drawImage(img, 10, 10);
        };
        img.src = src;
    }
    init();
  </script>
  </body>
</html>

这仅适用于支持画布 ex 的浏览器:Chrome(ium)

我也建议你阅读这个

于 2013-06-07T23:53:30.680 回答
0

这是您尝试的第一种方法吗?如果您只是想在网站上添加图像并将鼠标悬停在其上,则有一种更简单的方法。

首先,不要使用 Javascript 来创建和加载图像,而是使用 HTML<img>标记,例如:

<img src="http://earthbounds.com/banners/amazing food.jpg">

现在添加一个简单的悬停图像更改,这不是最佳实践,但作为一个示例,对于单个图像,您可以使用onmouseoverand onmouseout,例如:

<img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')">

现在要使此图像成为您使用<a>标签的另一个页面或网站的链接,例如:

<a href="www.google.ca"><img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')"></a>

希望这会有所帮助,并继续寻找和学习!

于 2013-06-07T23:56:01.870 回答