我试图用精灵设置一些图像对象(工作得非常好)(停止运行良好..):
抬头:代码简化了!
HTML 的
<canvas id="canvasMap" width="600" height="600"></canvas>
<div id="playerLeft"></div>
JS
var canvas = document.getElementById('canvasMap');
var context = canvas.getContext('2d');
var img = new Image();
img.src = $($(document).find('#playerLeft').get(0)).css('background').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
img.onload = function () {
context.drawImage(img, 0, 0);
};
CSS
#playerLeft {
left: 0px;
height:58px;
display:block;
width: 80px;
background: url('/assets/sprites/angle.png') -0px -70px;
}
RESULT(开发者控制台)
Resource interpreted as Image but transferred with MIME type text/html: "http://example.com/rgba(0,%200,%200,%200)%20url(http://example.com/assets/spr…png)%20repeat%20scroll%200px%20-70px%20/%20auto%20padding-box%20border-box"
问题
我如何制作它,声明的图像对象通过css定义的id接收背景精灵?我想在没有第三方lib的情况下解决它。
答案 0 :(得分:1)
以下是获取div背景图片的dataURL的一种方法:
// get the dataURL of your div's background
var bg = $('#sprite1').css('background-image');
bg = bg.replace('url(','').replace(')','').replace('"','').replace('"','');
示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// get the dataURL of your div's background
var bg = $('#sprite1').css('background-image');
bg = bg.replace('url(','').replace(')','').replace('"','').replace('"','');
// build an image from the dataURL
var img=new Image();
//img.crossOrigin='anonymous';
img.onload=function(){
// draw the image onto the canvas
ctx.drawImage(img,20,20);
}
img.src=bg;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
#sprite1{
border:1px solid blue;
width:75px;
height:75px;
background-image:url('https://dl.dropboxusercontent.com/u/139992952/multple/sun.png');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id=sprite1>Sprite1</div>
<canvas id="canvas" width=100 height=100></canvas>