I need to get the color of any pixel my mousepointer is currently hovering.
I found several solutions for canvas elements, but none for a background image defined in CSS for a element.
How can I achieve this?
Combining the answers from Get a CSS value with JavaScript and How to get a pixel's x,y coordinate color from an image?, I was able to simulate what you are looking for: JSFiddle
<html>
<head>
<style type="text/css">
#test {
background-image: url('http://jsfiddle.net/img/logo.png');
background-color: blue;
background-repeat: no-repeat;
height: 30px;
width: 100%;
}
#hidden {
display: none;
}
</style>
<script type="text/javascript">
var div = document.getElementById("test");
var style = window.getComputedStyle(div);
div.onmousemove = function(e) {
var path = style.getPropertyValue('background-image');
path = path.substring(4, path.length-1);
var img = document.getElementById("i1");
img.src = path;
var canvas = document.getElementById("c1");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;
var values = document.getElementById("values");
values.innerHTML = 'R: ' + pixelData[0] + '<br>G: ' + pixelData[1] + '<br>B: ' + pixelData[2] + '<br>A: ' + pixelData[3];
};
</script>
</head>
<body>
<div id="test"></div>
<div id="hidden">
<img id="i1" src="" />
<canvas id="c1"></canvas>
</div>
<div id="values"></div>
</body>
</html>
I retrieved the computed style (var style = window.getComputedStyle(div);) outside of the mouse move function for performance reasons, but if the background image is going to change dynamically, then it may need to be moved into the function.
There are some possible browser constraints for using getComputedStyle.
SCALING
You could try editing the code to adjust for the scale:
var h = parseInt(style.getPropertyValue("width")),
w = parseInt(style.getPropertyValue("height"));
var img = document.getElementById("i1");
img.src = path;
var canvas = document.getElementById("c1");
canvas.width = h;
canvas.height = w;
canvas.getContext('2d').drawImage(img, 0, 0, w, h);
This also includes a change to the CSS: JSFiddle
Related
I have seen in a couple of cases of converting text into images but nobody mention that if a text is too long i-e more then 1000 words how can I display them in image with using a font size of 15px
my HTML code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
</head>
<body>
<div id="the_text"></div>
<button id="show_img_btn">Convert to Image</button>
<div id="show_img_here"></div>
</body>
my Script code
window.onload=function(){
$("#show_img_btn").on("click", function () {
var canvas = document.createElement("canvas");
canvas.width = 620;
canvas.height = 80;
var ctx = canvas.getContext('2d');
ctx.font = "30px Arial";
var text = $("#the_text").text();
ctx.fillText(text,10,50);
var img = document.createElement("img");
img.src=canvas.toDataURL();
$("#show_img_here").append(img);
//$("body").append(canvas);
});
};
My question is if I convert this image it will converted into one line help me how can i convert the whole text into image and set the height and width.
Create a dummy element and apply same style props, append to dom and get the with of it. based on that you can split the text. Helpful snippet given below.
// JS:
function getDimen(text) {
var div = document.getElementById("dummy");
div.innerHTML = text
var h = (div.clientHeight + 1) + "px";
var w = (div.clientWidth + 1) + "px"
return({ h, w })
}
console.log(getDimen("some text hi a a s a a s as a s as a s as a s as a s"))
// HTML
<div id="dummy"></div>
// CSS:
#dummy {
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap;
}
I have a .js file with a simple animation that I'd like to use as a website's background. I'm able to put it onto the page and all that- but the text appears below the animation instead of over it. I've tried looking up solutions but all I've been able to find is instructions for making setting a .png/.jpg as the background. I'm very new to programming, so I haven't the slightest idea how I'd do this. Thanks for any help.
EDIT: Here's the code I'm trying to use!
<!DOCTYPE html>
<html>
<head>
<title>Scrolling Page</title>
</head>
<body style="background-color: black;">
<canvas id="canvas1"></canvas>
<h1>Text</h1>
<p>text</p>
</body>
</html>
<script src="mainscript.js"></script>
mainscript.js is:
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
can.width = 9200;
can.height = 630;
var img = new Image();
img.src = "tempimage.png";
window.onload = function() {
var imgWidth = 0;
var scrollSpeed = 10;
function loop()
{
ctx.drawImage(img, imgWidth, 0);
ctx.drawImage(img, imgWidth - can.width, 0);
imgWidth -= scrollSpeed;
if (-imgWidth == can.width)
imgWidth = 0;
window.requestAnimationFrame(loop);
}
loop();
Because we're not talking about using just a picture as a background and instead an HTML canvas element that is being animated, you'll need to use CSS to layer the canvas element that you want to use as a background behind the rest of the page content. To do that, you can position the background element with position:absolute and then place it behind everything else with z-index:-1.
<!DOCTYPE html>
<html>
<head>
<title>Scrolling Page</title>
<style>
#canvas1 {
position:absolute; /* Take the element out of the normal document flow */
z-index:-1; /* Place the element behind normal content */
top:0; /* Start at top of viewport */
left:0; /* Start at left edge of viewport */
}
</style>
</head>
<body>
<canvas id="canvas1"></canvas>
<h1>Text</h1>
<p>text</p>
<script>
var can = document.getElementById("canvas1");
var ctx = can.getContext('2d');
can.width = 9200;
can.height = 630;
var img = new Image();
img.src = "https://cdn.pixabay.com/photo/2019/02/19/19/45/thumbs-up-4007573__340.png";
window.onload = function() {
var imgWidth = 0;
var scrollSpeed = 10;
function loop() {
ctx.drawImage(img, imgWidth, 0);
ctx.drawImage(img, imgWidth - can.width, 0);
imgWidth -= scrollSpeed;
if (-imgWidth == can.width) {
imgWidth = 0;
}
window.requestAnimationFrame(loop);
}
loop();
}
</script>
</body>
</html>
I want to show a timelapse video but have it with a Range slider so the user can drag it back and forth. I've tried with a video but I don't like the loading effect as you scroll. I also exported the video as images and binded it to the range slider. First question is, isn't there any plugins or applications out there that do this? Maybe i'm searching the wrong terms. Second is an image sequence the best way to do this? In my code below I can get it to partially work, but I can't figure out how to resize the image, and it's way to big for the canvas.
<style>
canvas {
height: 650px;
width: 1000px;
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<canvas id="canvas" height="650px" width="1000px"></canvas>
<br>
<input id="my-input" type="range" min="1" max="50" value="1">
<script type="text/javascript">
var canvas = document.getElementById("canvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
var totalImages = 50;
var videoFrames = [];
for (var i = 1; i <= totalImages; i++) {
var videoFrame = new Image;
var videoFrameUrl = 'http://dacwebdesign.com/testing/images/timelapse-' + i + '.jpg';
videoFrame.src = videoFrameUrl;
videoFrames.push(videoFrame);
}
$("#my-input").on("input", function(event) {
var currentImage = videoFrames[event.target.value - 1];
var context = canvas.getContext("2d");
context.drawImage(currentImage, 0, 0);
});
</script>
You can resize the images to fit your canvas with:
var currentImage = videoFrames[event.target.value - 1];
var context = canvas.getContext("2d");
var dstWidth = canvas.width;
var dstHeight = canvas.height;
var srcWidth = currentImage.naturalWidth;
var srcHeight = currentImage.naturalHeight;
context.drawImage(currentImage, 0, 0, srcWidth, srcHeight, 0, 0, dstWidth, dstHeight);
That does not take into account aspect ratios, so if your canvas has a different aspect ratio to your images, it will appear distorted.
We currently upload an image via the below code:
reader.onload = function (event) {
fabric.Image.fromURL(event.target.result, function (img) {
whiteboardService.uploadImageToCanvas(img);
});
}
and...
service.uploadImageToCanvas = function (image) {
service.canvas.add(image);
image.id = service.getUniqueId();
service.objectMap[image.id] = image;
var data = {
image: image,
id: image.id
};
signalService.sendMessage(service.recipient, data);
};
If the image is too large, bigger than our fixed width and height of the canvas would it be possible for that image to be scaled down automatically to fit into the fixed width and height of the canvas?
I should point out that I am using Angular.js as well
ta
fabricjs put a very simple method to do this.
Those methods are scaleToWidth and scaleToHeight that are close to 'apply a scale factor that will fit the image on the specified dimensions'
So you can do
image.scaleToWidth(service.canvas.getWidth());
service.canvas.add(image);
it depends if you want to preserve aspect ratio if you have to scale for the biggest, the smallest or both.
Inspired by #AndreaBogazzi, I wrote below code to fit image to canvas totally.
var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('https://d32ogoqmya1dw8.cloudfront.net/images/NAGTWorkshops/structure/SGT2012/activities/noaa_global_topographic_map.jpg', function(oImg) {
let imgWidth = oImg.width;
let imgHeight = oImg.height;
let canvasWidth = canvas.getWidth();
let canvasHeight = canvas.getHeight();
let imgRatio = imgWidth / imgHeight;
let canvasRatio = canvasWidth / canvasHeight;
if(imgRatio <= canvasRatio){
if(imgHeight> canvasHeight){
oImg.scaleToHeight(canvasHeight);
}
}else{
if(imgWidth> canvasWidth){
oImg.scaleToWidth(canvasWidth);
}
}
canvas.clear();
canvas.add(oImg);
canvas.centerObject(oImg);
});
.image-preview{
border: solid 1px #979797;
width: 200px;
height: 200px;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
<div class="image-preview">
<canvas id="canvas" width='200' height='200'></canvas>
<hr/>
<p>Origin Image</p>
<img src="https://d32ogoqmya1dw8.cloudfront.net/images/NAGTWorkshops/structure/SGT2012/activities/noaa_global_topographic_map.jpg" />
</div>
I'm learning JavaScript and HTML 5.
I simply cannot get a simple border around the canvas. The html completely ignores the css.
Here's my code:
JavaScript:
function buildCanvas()
{
var w = window.innerWidth / 2;
var h = window.innerHeight / 2;
document.write("<CANVAS WIDTH=" + w + " HEIGHT=" + h + " ID=canvas_1>");
document.write("</CANVAS>");
drawOnCanvas();
}
function drawOnCanvas()
{
var canvas = document.getElementById("canvas_1");
if (canvas.getContext)
{
var canvas_context = canvas.getContext("2d");
canvas_context.font = "84px Ariel";
canvas_context.fillText("Test", 500, 300);
}
}
HTML:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<LINK rel="stylesheet" type="text/css" href="css/style.css">
<TITLE>Canvas Test</TITLE>
<SCRIPT LANGUAGE="JavaScript" SRC="scripts/external.js"></SCRIPT>
</HEAD>
<BODY onLoad="buildCanvas()">
</BODY>
</HTML>
STYLESHEET:
canvas
{
border: 1px solid black;
}
You are calling document.write after the document has loaded (ie. during the onload event). This replaces the current document with a new one containing your new content. In short, it nukes the page, including style definitions.
Try this instead:
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
canvas.id = "canvas_1";
document.body.appendChild(canvas);