技术问询:能否实现屏幕绘图跨区域平移及A到B区域绘图映射?
Hey Kriso, let's tackle your two graphics translation/mirroring questions—these are really common tasks in any 2D graphics workflow, so I’ll break down practical ways to implement both:
Absolutely doable, and the approach depends on whether you’re working with a fresh draw or moving already-rendered content. Here’s how to handle both cases (using HTML5 Canvas as an example, but the logic translates to other frameworks like Qt, JavaFX, etc.):
For fresh content (draw directly to the target area):
Use coordinate translation to shift your drawing context. Just remember to save/restore the context state so you don’t mess up future draws:const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // Save the original context state ctx.save(); // Shift the entire coordinate system to your target position (e.g., 150px right, 100px down) ctx.translate(150, 100); // Draw your content as if you're starting at (0,0) ctx.fillStyle = 'red'; ctx.fillRect(0, 0, 50, 50); // This will appear at (150, 100) instead of (0,0) // Restore the original context so subsequent draws aren't shifted ctx.restore();For already-rendered content (copy existing pixels):
UsedrawImageto clone a portion (or the whole) of your canvas to a new location:// Copy the entire canvas content to (200, 200) ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 200, 200, canvas.width, canvas.height); // Or copy just a specific region (e.g., (0,0) to (100,100)) to (300, 300) ctx.drawImage(canvas, 0, 0, 100, 100, 300, 300, 100, 100);
Yes, this is totally achievable—you have two main strategies depending on whether you need real-time sync or a one-time copy:
Real-time synchronized drawing:
Whenever you draw something in Area A, replicate the same action in Area B with adjusted coordinates. For example, if Area A is(0,0) to (100,100)and Area B is(200,200) to (300,300), every point(x,y)in A maps to(x+200, y+200)in B. Wrap this logic in a reusable function:function drawInBothAreas(x, y, shapeSize) { // Draw in Area A ctx.fillStyle = 'green'; ctx.fillRect(x, y, shapeSize, shapeSize); // Draw the same shape in Area B (offset by 200px in both axes) ctx.fillRect(x + 200, y + 200, shapeSize, shapeSize); } // Usage: Draw a square at (20,20) in A and (220,220) in B drawInBothAreas(20, 20, 30);If you’re handling user input (like mouse drawing), listen to events (e.g.,
mousemove,mousedown) and call this function every time the user draws in Area A.One-time static copy:
If you just need to mirror existing content from A to B once, usedrawImageto copy the pixel data directly:// Copy Area A (0,0 to 100,100) to Area B (200,200 to 300,300) ctx.drawImage(canvas, 0, 0, 100, 100, 200, 200, 100, 100);
The core idea here is either duplicating the drawing logic with coordinate offsets or copying pixel data between regions—both work reliably across most 2D graphics libraries.
内容的提问来源于stack exchange,提问作者Kriso

