【问题标题】:Canvas drawImage by division background sprites通过分割背景精灵画布绘制图像
【发布时间】:2015-01-19 20:21:18
【问题描述】:

我正在尝试使用精灵在画布元素中设置一些图像对象(效果很好)(停止正常工作..):

注意:代码已简化!

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;
}

结果(开发者控制台)

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 接收背景精灵?我想在没有第三方库的情况下解决它。

【问题讨论】:

标签: javascript canvas sprite


【解决方案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>

【讨论】:

  • 是的,这就是如何使用一个部门的整个背景图像。但我只需要一部分。这就是我们使用精灵的原因。我不需要整个图像。那么,你能告诉我,如何制作这个吗?
  • 当然,一旦你有了整个背景图像,你就可以使用 context.drawImage 的剪辑版本从整个图像中剪辑你想要的精灵。如果您之前没有使用过该版本的 drawImage,这里有一个链接:developer.mozilla.org/en-US/docs/Web/API/…。祝你的项目好运!
  • 这太棒了,正是我正在寻找的!
猜你喜欢
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
相关资源
最近更新 更多