像素艺术在浏览器中很困难,主要是由于缺乏对“像素化”或“边缘清晰”图像渲染的通用浏览器支持。它应该在 CSS4 中得到支持。
目前 CSS 堆栈看起来像这样,尽管 Chrome 30 和 Opera 16 似乎已经破坏了对 CSS 解决方案的支持
image-rendering:optimizeSpeed;
image-rendering:-moz-crisp-edges;
image-rendering:-o-crisp-edges;
image-rendering:optimize-contrast;
image-rendering:-webkit-optimize-contrast;
-ms-interpolation-mode: nearest-neighbor;
请参阅@Phrogz 的这个答案,并附上一个测试用例。另请参阅Mozilla关于该主题的文档。对于现在的普遍支持,一个 JS 解决方案可能暂时必须工作,例如在伟大的文章中看到这里绘制像素很难:
var resize = function( img, scale ) {
// Takes an image and a scaling factor and returns the scaled image
// The original image is drawn into an offscreen canvas of the same size
// and copied, pixel by pixel into another offscreen canvas with the
// new size.
var widthScaled = img.width * scale;
var heightScaled = img.height * scale;
var orig = document.createElement('canvas');
orig.width = img.width;
orig.height = img.height;
var origCtx = orig.getContext('2d');
origCtx.drawImage(img, 0, 0);
var origPixels = origCtx.getImageData(0, 0, img.width, img.height);
var scaled = document.createElement('canvas');
scaled.width = widthScaled;
scaled.height = heightScaled;
var scaledCtx = scaled.getContext('2d');
var scaledPixels = scaledCtx.getImageData( 0, 0, widthScaled, heightScaled );
for( var y = 0; y < heightScaled; y++ ) {
for( var x = 0; x < widthScaled; x++ ) {
var index = (Math.floor(y / scale) * img.width + Math.floor(x / scale)) * 4;
var indexScaled = (y * widthScaled + x) * 4;
scaledPixels.data[ indexScaled ] = origPixels.data[ index ];
scaledPixels.data[ indexScaled+1 ] = origPixels.data[ index+1 ];
scaledPixels.data[ indexScaled+2 ] = origPixels.data[ index+2 ];
scaledPixels.data[ indexScaled+3 ] = origPixels.data[ index+3 ];
}
}
scaledCtx.putImageData( scaledPixels, 0, 0 );
return scaled;
}
通读这篇文章,Retina 显示器和移动 Safari 的存在可能会增加渲染正确尺寸像素艺术的额外复杂性。尽管使用 iOS7 的移动 safari,这可能会得到纠正。