*{margin: 0padding: 0}
.wrap{width: 500pxheight: 500pxborder: 1px solid #cccbackground: #eeemargin: 30px autoposition: relativeoverflow: hidden}
.box{position: absolutetop: 510pxwidth: 50pxheight: 50pxtext-align: centerline-height: 50pxfont-size: 22pxfont-weight: boldcolor: #666}
</style>
<div class="wrap">
</div>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var qiqiu={
num:0,
wrap: $(".wrap"),
box:null,
createStr: function(){
var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.:/?|\""
return s[parseInt(s.length*Math.random())]
},
create: function(){
var ele = $("<div class='box' />").appendTo(this.wrap)
ele.html(this.createStr())
ele.data("code",ele.html().charCodeAt(0))
ele.css({
"left": (this.wrap.width()-50)*Math.random()
})
if(!this.box){
this.box = ele
}else {
this.box = this.box.add(ele)
}
setTimeout(function(){
qiqiu.create()
},2000)
},
move: function(){
this.timer = setInterval(function(){
qiqiu.box.css({
top: "-=3"
})
},25)
},
stop: function(){
clearInterval(this.timer)
},
destroy: function(inx){
this.box.eq(inx).css({
"color":"red",
"background":"#ffe"
}).fadeOut(100,function(){
qiqiu.box.eq(inx).remove()
})
},
hit: function(s){
this.box.each(function(inx,ele){
if($(this).data("code")===s){
qiqiu.destroy(inx)
return false
}
})
},
init: function(){
$(document).on({
"keypress": function(e){
qiqiu.hit(e.which)
return false
}
})
this.create()
this.move()
}
}
qiqiu.init()
</script>
通常有两种方法从画布获取图像:>使用getimageData()获取画布给定矩形的每个像素的rgba值.
>使用toDataURL()获取整个画布的Base64字符串.
第二种方法可能是最有用的,并结合一些HTML5魔法和下载属性,我们可以创建可下载的图像或将字符串发送到服务器并将其保存为图像:
var base64 = d_canvas.toDataURL("image/png")
var a = document.createElement('a')
a.href= base64,
a.target = '_blank'
a.download= 'myImage.png'
document.body.appendChild(a)
a.click()
如果你需要将气球放在特定的地方,移动它应该是微不足道的.
这是一个
FIDDLE
请注意,我必须删除外部图像并使用base64来避免画布中的跨源图像.