Home >Web Front-end >CSS Tutorial >How to Stretch Images Without Antialiasing in the Browser?
Stretching Images Without Antialiasing in the Browser
Stretching images without antialiasing is a common challenge faced by web developers, particularly when dealing with pixel art. Traditionally, methods such as CSS, JavaScript, and HTML have been used to stretch images, but they often introduce undesirable blurring due to antialiasing.
CSS and Modern Browsers
Recent versions of Chrome and Firefox introduced a new CSS property called image-rendering. By setting this property to pixelated, it is possible to disable antialiasing when stretching images. However, this method is not yet reliable, as Chrome and FF have discontinued support for it.
Canvas-Based Solution
The Canvas API provides a solution for stretching images without antialiasing. The code below demonstrates how to create a scaled image on a canvas:
<code class="javascript">var img = new Image(); img.onload = function() { var scale = 8; var src_canvas = document.createElement('canvas'); src_canvas.width = this.width; src_canvas.height = this.height; var src_ctx = src_canvas.getContext('2d'); src_ctx.drawImage(this, 0, 0); var src_data = src_ctx.getImageData(0, 0, this.width, this.height).data; var dst_canvas = document.getElementById('canvas'); dst_canvas.width = this.width * scale; dst_canvas.height = this.height * scale; var dst_ctx = dst_canvas.getContext('2d'); var offset = 0; for (var y = 0; y < this.height; ++y) { for (var x = 0; x < this.width; ++x) { var r = src_data[offset++]; var g = src_data[offset++]; var b = src_data[offset++]; var a = src_data[offset++] / 100.0; dst_ctx.fillStyle = 'rgba(' + [r, g, b, a].join(',') + ')'; dst_ctx.fillRect(x * scale, y * scale, scale, scale); } } };</code>
This code copies pixel data from a source image to a scaled destination canvas, effectively stretching the image without antialiasing.
The above is the detailed content of How to Stretch Images Without Antialiasing in the Browser?. For more information, please follow other related articles on the PHP Chinese website!