var canvas = document.getElementByIdx_x_x_x_x_x_x("lesson01")
if(canvas.getContext)
{
var context = canvas.getContext("2d")
var pic = new Image()
pic.onload=function(){
context.drawImage(pic,0, 0)
}
pic.src = "http://imgsrc.baidu.com/forum/pic/item/e6b14bc2a4561b1fe4dd3b24.jpg"
}
}
下面写一个例子关于利用canvas实现图片变灰的code.
<html>
<head>
<script>
window.onload = function () {
var canvas = document.getElementByIdx_x_x_x("myCanvas")
var image = document.getElementByIdx_x_x_x("imageSource")
// 将图片的高宽赋值给画布
canvas.width = image.width
canvas.height = image.height
// 获得二维渲染上下文
if (canvas.getContext) {//为了安全起见,先判断浏览器是否支持canvas
var context = canvas.getContext("2d")
context.drawImage(image, 0, 0)//将得到的image图像绘制在canvas对象中
var canvasData = context.getImageData(0, 0, canvas.width, canvas.height)//返回ImageData对象
alert(canvasData.width.toString())
alert(canvasData.height.toString())
for (var x = 0x <canvasData.widthx++) {
for (var y = 0y <canvasData.heighty++) {
// Index of the pixel in the array
var idx = (x + y * canvasData.width) * 4
var r = canvasData.data[idx + 0]
var g = canvasData.data[idx + 1]
var b = canvasData.data[idx + 2]
// 灰度的计算
var gray = .299 * r + .587 * g + .114 * b
// assign gray scale value
canvasData.data[idx + 0] = gray// Red channel
canvasData.data[idx + 1] = gray// Green channel
canvasData.data[idx + 2] = gray// Blue channel
canvasData.data[idx + 3] = 255// Alpha channel
// 新增黑色边框
if (x <8 || y <8 || x >(canvasData.width - 8) || y >(canvasData.height - 8)) {
canvasData.data[idx + 0] = 0
canvasData.data[idx + 1] = 0
canvasData.data[idx + 2] = 0
}
}
}
context.putImageData(canvasData, 0, 0)// 处理完成的数据重新载入到canvas二维对象中
} else {
alert("your browser does not support canvas!")
}
}
</script>
</head>
<body>
<h2>Hello World!</h2>
<img id="imageSource" src="1.jpg" alt="Canvas Source" />
<canvas id="myCanvas" >Gray Filter</canvas>
</body>
</html>
请问要蒙上什么样的一层灰色?1. bosonbai说的 opacity 是控制元素的透明度,filter的写法是IE适用,
还可以写成 opacity:0.7 ,兼容Chrome
2. 如果是需要一层半透明黑灰色,挡着图片,你需要弄一个position: absolutebackground:#000opacity:.7的div遮挡,注意宽度高度,和位置
3. 如果是想让图片变成黑白色,需要 filter: grayscale(100%),具体可以自行搜索
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)