将图像从CSS链接到Javascript

时间:2014-12-13 01:52:19

标签: javascript css image

我想将CSS中的图像链接到Javascript,但我的代码不起作用。

CSS:

.backImage {

    background-image: url("img/level1.jpg");
    background-repeat: repeat-y;

}

Javascript代码:

var x1 = 450;
var y1 = 40;
var speed1 = 5;
var angle1 = 90;
var mod1 = 1;        

var tmp= $("<div>").addClass('backImage');
var src = tmp.css('background-image').match(/[^"][^"]+/g)[1];

console.log(src);

var back = new Image();
    back.src = src;  

function drawBackground() {

    x1 += (speed1 * mod1) * Math.cos(Math.PI / 180 * angle1);
    y1 += (speed1 * mod1) * Math.sin(Math.PI / 180 * angle1);

    context.save();
    context.translate(x1, y1);
    context.rotate(Math.PI / 180 * angle1);
    context.drawImage(back, -(back.width / 2), -(back.height / 2));
    context.restore();

} 

1 个答案:

答案 0 :(得分:1)

我猜你想要从CSS background-image源中提取图像并在画布上绘制它。这就是它的完成方式。

&#13;
&#13;
var tmp = $("<div>").addClass('backImage');
var src = tmp.css('background-image').match(/[^"][^"]+/g)[1];
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');

console.log(src);

var back = new Image();
back.src = src;
back.onload = drawBackground;

function drawBackground() {
  canvas.width = back.width;
  canvas.height = back.height;
  context.drawImage(back, 0, 0);
}
&#13;
.backImage {
  background-image: url("http://placehold.it/200/200");
  background-repeat: repeat-y;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;